package com.example.redissession.dlm;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author: cph
 * @date: 2022/3/18 17:03
 */
@Slf4j
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return SpringContextUtil.applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static Object getBean(String name) {
        try {
            checkApplicationContext();
            return getApplicationContext().getBean(name);
        } catch (Exception e) {
            log.error("SpringContextUtil#getBean异常...name", e);
            return null;
        }
    }

    public static <T> T getBean(Class<T> clazz) {
        try {
            checkApplicationContext();
            return getApplicationContext().getBean(clazz);
        } catch (Exception e) {
            throw new RuntimeException("SpringContextUtil#getBean异常...clazz", e);
        }
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        try {
            checkApplicationContext();
            return getApplicationContext().getBean(name, clazz);
        } catch (Exception e) {
            log.error("SpringContextUtil#getBean异常...name,clazz");
            return null;
        }
    }

    private static void checkApplicationContext() {
        if (Objects.isNull(applicationContext)) {
            throw new RuntimeException("SpringContextUtil中applicationContext为空!");
        }
    }

}
